<!-- 选择项目发票弹窗 -->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="选择项目发票"
    width="70%"
    draggable
    overflow
    @close="handleClose"
  >
    <div class="crossRope" />
    <el-form label-width="120px" style="margin-top: 2%">
      <el-row>
        <el-col :span="10">
          <el-form-item label="开票时间">
            <el-date-picker
              v-model="searchForm.invoicingDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button
            color="#1E3485"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getList();
            "
            >搜索</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      ref="xTable"
      border
      min-height="350"
      max-height="550"
      header-align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="tableData"
      size="mini"
      :loading="tableLoading"
      :pager-config="tablePage"
      @checkbox-change="checkboxChange"
    >
      <vxe-column type="checkbox" width="60" align="center" />
      <vxe-column
        v-for="column in tableColumns"
        :key="column.field"
        :field="column.field"
        :title="column.title"
        :min-width="column.width"
        :align="column.align"
        header-align="center"
        show-overflow
      >
        <template v-slot:default="{ row }">
          {{ row[column.field] }}
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-pager
      v-model:current-page="tablePage.currentPage"
      v-model:page-size="tablePage.pageSize"
      :layouts="[
        'Sizes',
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'FullJump',
        'Total'
      ]"
      :total="tablePage.total"
      size="mini"
      style="margin-top: 2%"
      @page-change="handlePageChange"
    />
    <div class="crossRope" />
    <div style="text-align: right; margin-top: 2%">
      <el-button
        color="#1E3485"
        :icon="Select"
        size="small"
        @click="selectConfirm"
        >确定</el-button
      >
      <el-button :icon="CloseBold" size="small" @click="handleClose"
        >关闭</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElDialog, ElMessage, ElMessageBox } from "element-plus";
import { Select, CloseBold, Search } from "@element-plus/icons-vue";
import { VxePagerEvents, VxeTable } from "vxe-table";
import {
  getRelatedInvoiceList,
  getFindByTypeList,
  relatedInvoice,
  relationInvoice
} from "@/api/ERP_InvoiceManage";

///////////////////////// 公共 /////////////////////////
// 弹窗关闭/打开
const props = defineProps({
  visible: Boolean,
  id: String,
  data: Object
});
const dialogFormVisible = ref(false);
const emit = defineEmits(["close"]);
function handleClose() {
  emit("close", false);
}
watch(
  () => props.visible,
  val => {
    dialogFormVisible.value = val;
  },
  { immediate: true }
);
///////////////////////// 数据展示 /////////////////////////
// 表单数据
let searchForm = reactive({
  contractId: "",
  invoicingDate: [],
  invoiceDataType: "0" // 发票数据类型 0-云采开票 1-供应商开票
  // invoiceBindStatus: "0", // 发票绑定状态 0-未绑定 1-已绑定
  // invoicingStatus: "6" // 开票状态
});
// 表格配置
let tableData = ref([]);
let tableLoading = ref(false);
const selectedRow = ref(null as any);
let xTable = ref(null);
const tableColumns = reactive([
  {
    field: "invoicingDate",
    title: "开票时间",
    width: 120,
    align: "center"
  },
  {
    field: "invoicingPrice",
    title: "开票金额",
    width: 120,
    align: "right"
  },
  {
    field: "projectName",
    title: "项目名称",
    width: 180,
    align: "left"
  },
  {
    field: "supplierDeptName",
    title: "开票单位",
    width: 120,
    align: "center"
  },
  {
    field: "invoicingCode",
    title: "开票代码",
    width: 120,
    align: "center"
  },
  {
    field: "invoicingNo",
    title: "开票号码",
    width: 120,
    align: "center"
  }
]);
// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
// 表格选中行
function checkboxChange({ records, checked }) {
  if (records.length > 0) {
    selectedRow.value = [];
    for (let i in records) {
      selectedRow.value.push(records[i].id);
    }
  } else {
    selectedRow.value = null;
  }
}
///////////////////////// 数据请求 /////////////////////////
// 获取表格数据
async function getList() {
  tableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  for (let key in searchForm) {
    if (searchForm[key] && key != "invoicingDate") {
      params[key] = searchForm[key];
    }
  }
  if (searchForm.invoicingDate) {
    params.beginDate = searchForm.invoicingDate[0];
    params.endDate = searchForm.invoicingDate[1];
  }
  try {
    const response: ApiResponse = await getFindByTypeList(params);
    if (response.code === 200) {
      tableData.value = response.data.records;
      tablePage.total = response.data.totalElements;
    } else {
      ElMessage.error("获取表格数据失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    tableLoading.value = false;
  }
}
// 确认事件
function selectConfirm() {
  if (!selectedRow.value) {
    ElMessage.error("请选择一条数据！");
    return;
  }
  ElMessageBox.confirm("确认关联所选发票吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params: ApiParams = {};
      params.invoiceBindId = props.data.id;
      params.relationInvoiceIds = selectedRow.value;
      try {
        const response: ApiResponse = await relationInvoice(params);
        if (response.code === 200) {
          ElMessage.success("关联成功");
          emit("close", false);
        } else {
          ElMessage.error("关联失败: " + response.msg);
        }
      } catch (error) {}
    })
    .catch(() => {
      ElMessage.warning("已取消！");
    });
}
///////////////////////// 公共 /////////////////////////
// 打开弹窗时执行
watch(dialogFormVisible, newValue => {
  if (newValue) {
    searchForm.contractId = props.id;
    getList();
  }
});
</script>

<style lang="scss" scoped></style>
